package com.xxxx.paipaicars.config.interceptor;

import com.xxxx.paipaicars.config.auth_phase.AccessPhase;
import com.xxxx.paipaicars.config.auth_phase.ICommonAccessPhase;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 登录的拦截器
 * Created by frank on 2023/2/14.
 */
@SuppressWarnings("all")
@Slf4j
@Configuration
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     //TODO:登入器的拦截器第一步进行获取到所拦截的方法
        String methods = request.getMethod();
     //TODO:对拦截的方法进行判断是否为复杂请求
        if(methods.equals("OPTIONS")){
            response.setStatus(200);
            //若为复杂请求
            return false;
        }

     //TODO:第二步进行 对注解是否映射到方法上 若不是则直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 当前请求可以映射到一个方法上
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取到当前的方法
        Method method = handlerMethod.getMethod();
        //TODO:第三步进行 对有贴注解的方法进行解析
        if(method.isAnnotationPresent(AccessPhase.class)){
            //TODO:若有贴注解 则获取该权限名
            AccessPhase accessPhase = method.getAnnotation(AccessPhase.class);
            String[] name = accessPhase.name();
            for (int i = 0; i <name.length ; i++) {
                Class className = Class.forName(name[i]);
                //进行实例化
                ICommonAccessPhase commonAuthentication = (ICommonAccessPhase) className.newInstance();
                Boolean result = commonAuthentication.accessPhase(request, response);
                // 200代表验证成功，否则直接返回
                return result;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
